# -*- coding: utf-8 -*-
# filename: nbiot_server.py

import socket
import pymysql
import re
from mysql_login_info import MYSQL_HOST, MYSQL_ACCOUNT, MYSQL_PASSWORD, MYSQL_DATABASE, MYSQL_PORT
import sys

CmdTblDict = {
    'tp':'temp_tbl',
    'hm':'humi_tbl',
    'pm':'pm2_5_tbl',
    # 'fm':'form_tbl',
    # 'tl':'tolu_tbl',
    'cd':'co2_tbl'
}

def nbiot_server(port='8042'):
    # address = ('172.16.0.8', int(port))
    address = ('127.0.0.1', int(port))
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(address)

    try:
        db = pymysql.connect(MYSQL_HOST, MYSQL_ACCOUNT, MYSQL_PASSWORD, MYSQL_DATABASE, port=int(MYSQL_PORT))
    except Exception, err:
        print err
        return
    cursor = db.cursor()

    while True:
        try:
            udpData, udpAddr = s.recvfrom(255)
            reRst = re.findall('([a-z]{2}\d+(\.\d+)?)', udpData)
            print reRst
            for reOne in reRst:
                data = reOne[0]
                # print data
                tbl_name = None
                for key in CmdTblDict.keys():
                    if(data[0:2] == key):
                        tbl_name = CmdTblDict[key]
                # print tbl_name
                if(tbl_name != None):
                    try:
                        sql = "INSERT INTO {tbl} (val, ip, port) " \
                              "VALUES (\'{val}\', \'{ip}\', \'{port}\')" \
                            .format(tbl=tbl_name, val=float(data[2:]), ip=udpAddr[0], port=udpAddr[1])
                        # print sql
                        cursor.execute(sql)
                    except Exception, err:
                        print err
                    finally:
                        db.commit()
            # s.sendto(udpData, udpAddr)
        except Exception, err:
            db.close()
            s.close()
            print err
            return

if __name__ == '__main__':
    nbiot_server(sys.argv[1])
